package co.edu.eam.ingsoft.tlf.analizador.vista;

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

import co.edu.eam.ingsoft.tlf.analizador.logica.AnalizadorLexico;
import co.edu.eam.ingsoft.tlf.analizador.logica.SimboloLexico;

@SuppressWarnings("serial")
public class InterfazPrincipal extends JFrame {

	public static final int BUTTON_WIDTH = 30;
	public static final int BUTTON_HEIGHT = 30;

	private String currentFile;
	private AnalizadorLexico analizadorLexico;

	// private InterfazPrincipal this;
	private JToolBar toolBar;
	private JButton btnNuevo;
	private JButton btnAbrir;
	private JButton btnGuardar;
	private JButton btnGuardarComo;
	private JButton btnAnalizar;
	private JButton btnVerAutomatas;
	private JPanel panel;
	private JTabbedPane tabbedPane;
	private JPanel pnlLexemas;
	private JPanel pnlErrores;
	private JScrollPane scrollPane;
	private JTextPane txtPnCodigo;
	private JMenuBar menuBar;
	private JMenu mnArchivo;
	private JMenuItem mntmNuevo;
	private JMenuItem mntmAbrir;
	private JMenuItem mntmGuardar;
	private JMenuItem mntmGuardarComo;
	private JSeparator separator;
	private JMenuItem mntmSalir;
	private JMenu mnEjecutar;
	private JMenuItem mntmAnalizar;
	private JMenuItem mntmVerAutomatas;
	private JScrollPane scrollPaneLexemas;
	private JTable tableLexemas;
	private JScrollPane scrollPaneErrores;
	private JTable tableErrores;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {

					UIManager.setLookAndFeel(UIManager
							.getSystemLookAndFeelClassName());
					// InterfazPrincipal window = new InterfazPrincipal();
					// window.setVisible(true);
					DecimalFormat format = new DecimalFormat("#.00");
					double number = 6584.8457;
					System.out.println(format.format(number));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public InterfazPrincipal() {
		currentFile = "./res/codigo.txt";
		analizadorLexico = new AnalizadorLexico();
		initialize();
		resizeContainers();
		inicialLoad();

	}

	private void inicialLoad() {
		try {
			File file = new File(currentFile);
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String linea = "";
			String texto = "";

			while ((linea = reader.readLine()) != null) {
				texto += linea + "\n";
			}
			txtPnCodigo.setText(texto);
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void llenarTabla(ArrayList<SimboloLexico> list, JTable table) {
		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		dtm.setRowCount(0);
		SimboloLexico simboloLexico;
		for (int i = 0; i < list.size(); i++) {
			simboloLexico = (SimboloLexico) list.get(i);
			Object[] datos = new Object[4];
			datos[0] = simboloLexico.getFila();
			datos[1] = simboloLexico.getColumna();
			datos[2] = simboloLexico.getLexema();
			datos[3] = simboloLexico.getToken().getDescripcion();
			dtm.addRow(datos);
		}
		table.setModel(dtm);
	}

	private void runActionPerformed(ActionEvent event) {
		analizadorLexico = new AnalizadorLexico();
		analizadorLexico.analizar(txtPnCodigo.getText());
		llenarTabla(analizadorLexico.getTablaSimbolos(), tableLexemas);
		llenarTabla(analizadorLexico.getTablaErrores(), tableErrores);
	}

	private void openActionPerformed(ActionEvent event) {
		JFileChooser chooser = new JFileChooser(currentFile);
		int res = chooser.showOpenDialog(this);
		if (res == JFileChooser.APPROVE_OPTION) {
			try {
				currentFile = chooser.getSelectedFile().getAbsolutePath();
				File file = new File(currentFile);
				BufferedReader reader = new BufferedReader(new FileReader(file));
				String linea = "";
				String texto = "";

				while ((linea = reader.readLine()) != null) {
					texto += linea + "\n";
				}
				txtPnCodigo.setText(texto);
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void saveActionPerformed(ActionEvent event) {
		ImageIcon icon = new ImageIcon(
				InterfazPrincipal.class
						.getResource("/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/question.png"));
		int res = JOptionPane
				.showOptionDialog(
						this,
						"Esta seguro que desea guardar, \n el archivo original se modificara",
						"Confirmar la accion", JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE, icon, null, null);
		if (res == JFileChooser.APPROVE_OPTION) {
			try {
				File file = new File(currentFile);
				PrintWriter printWriter = new PrintWriter(file);
				String texto = txtPnCodigo.getText();
				printWriter.print(texto);
				printWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void saveAsActionPerformed(ActionEvent event) {
		JFileChooser chooser = new JFileChooser("./res");
		int res = chooser.showSaveDialog(this);
		if (res == JFileChooser.APPROVE_OPTION) {
			try {
				currentFile = chooser.getSelectedFile().getAbsolutePath();
				File file = new File(currentFile);
				PrintWriter printWriter = new PrintWriter(file);
				String texto = txtPnCodigo.getText();
				printWriter.print(texto);
				printWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void resizeContainers() {
		this.repaint();

		int x;
		int y;
		int width;
		int height;

		x = 5;
		y = 0;
		width = this.getWidth();
		height = 45;

		toolBar.setBounds(x, y, width, height);
		toolBar.updateUI();

		x = 5;
		y = toolBar.getHeight();
		width = this.getWidth() - 26;
		height = (this.getHeight() - (toolBar.getY() + toolBar.getHeight())) / 2;
		scrollPane.setBounds(x, y, width, height);
		scrollPane.updateUI();
		txtPnCodigo.updateUI();

		x = 5;
		y = scrollPane.getY() + scrollPane.getHeight();
		width = this.getWidth() - 18;
		height = this.getHeight()
				- (scrollPane.getY() + scrollPane.getHeight()) - 57;
		panel.setBounds(x, y, width, height);
		panel.updateUI();

		x = 0;
		y = 0;
		width = panel.getWidth() - 5;
		height = panel.getHeight() - 5;
		tabbedPane.setBounds(x, y, width, height);
		tabbedPane.updateUI();
	}

	public void verAutomatas() {
		try {
			String automatas = InterfazPrincipal.class.getResource(
					"/co/edu/eam/ingsoft/tlf/analizador/res/Automatas.pdf")
					.getPath();
			Desktop.getDesktop().open(new File(automatas));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				Icon icon = new ImageIcon(
						InterfazPrincipal.class
								.getResource("/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/question.png"));
				int retorno = JOptionPane.showConfirmDialog(null,
						"Desea guardar antes de salir?", "Guardar",
						JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE, icon);
				if (retorno == JOptionPane.YES_OPTION) {
					saveActionPerformed(null);
				}
			}
		});
		this.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				resizeContainers();
			}
		});
		this.setTitle("Analizador Lexico");
		// frmAnalizadorLexico.setSize(450, 460);
		this.setMinimumSize(new Dimension(450, 460));
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.getContentPane().setLayout(null);
		this.setLocationRelativeTo(null);
		this.setExtendedState(JFrame.MAXIMIZED_BOTH);

		toolBar = new JToolBar();
		toolBar.setRollover(true);
		toolBar.setFloatable(false);
		this.getContentPane().add(toolBar);

		String image;

		image = "/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/new.png";
		btnNuevo = new JButton();
		btnNuevo.setToolTipText("Nuevo");
		btnNuevo.setIcon(new ImageIcon(InterfazPrincipal.class
				.getResource(image)));
		btnNuevo.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
		toolBar.add(btnNuevo);

		image = "/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/open.png";
		btnAbrir = new JButton();
		btnAbrir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openActionPerformed(e);
			}
		});
		btnAbrir.setToolTipText("Abrir");
		btnAbrir.setIcon(new ImageIcon(InterfazPrincipal.class
				.getResource(image)));
		btnAbrir.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
		toolBar.add(btnAbrir);

		image = "/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/save.png";
		btnGuardar = new JButton();
		btnGuardar.setToolTipText("Guardar");
		btnGuardar.setIcon(new ImageIcon(InterfazPrincipal.class
				.getResource(image)));
		btnGuardar.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
		btnGuardar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveActionPerformed(e);
			}
		});
		toolBar.add(btnGuardar);

		image = "/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/saveAs.png";
		btnGuardarComo = new JButton();
		btnGuardarComo.setToolTipText("Guardar Como");
		btnGuardarComo.setIcon(new ImageIcon(InterfazPrincipal.class
				.getResource(image)));
		btnGuardarComo.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
		btnGuardarComo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveAsActionPerformed(e);
			}
		});
		toolBar.add(btnGuardarComo);

		image = "/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/run.png";
		btnAnalizar = new JButton();
		btnAnalizar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				runActionPerformed(e);
			}
		});
		btnAnalizar.setToolTipText("Analizar");
		btnAnalizar.setIcon(new ImageIcon(InterfazPrincipal.class
				.getResource(image)));
		btnAnalizar.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
		toolBar.add(btnAnalizar);

		image = "/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/search.png";
		btnVerAutomatas = new JButton();
		btnVerAutomatas.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				verAutomatas();
			}
		});
		btnVerAutomatas.setToolTipText("Ver Automatas");
		btnVerAutomatas.setIcon(new ImageIcon(InterfazPrincipal.class
				.getResource(image)));
		btnVerAutomatas.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
		toolBar.add(btnVerAutomatas);

		panel = new JPanel();
		panel.setSize(new Dimension(450, 0));
		this.getContentPane().add(panel);
		panel.setLayout(null);

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		panel.add(tabbedPane);
		{
			image = "/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/info.png";
			pnlLexemas = new JPanel();
			tabbedPane.addTab("Lexemas",
					new ImageIcon(InterfazPrincipal.class.getResource(image)),
					pnlLexemas, null);
			pnlLexemas.setLayout(new BorderLayout(0, 0));

			scrollPaneLexemas = new JScrollPane();
			pnlLexemas.add(scrollPaneLexemas, BorderLayout.CENTER);

			tableLexemas = new JTable();
			String[] columnNames = new String[] { "Fila", "Columna", "Lexema",
					"Token" };
			tableLexemas.setModel(new DefaultTableModel(columnNames, 0) {
				boolean[] columnEditables = new boolean[] { false, false,
						false, false };

				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			});
			for (int i = 0; i < columnNames.length; i++) {
				tableLexemas.getColumnModel().getColumn(i).setResizable(false);
			}
			scrollPaneLexemas.setViewportView(tableLexemas);
		}

		{
			image = "/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/error.png";
			pnlErrores = new JPanel();
			tabbedPane.addTab("Errores",
					new ImageIcon(InterfazPrincipal.class.getResource(image)),
					pnlErrores, null);
			pnlErrores.setLayout(new BorderLayout(0, 0));

			scrollPaneErrores = new JScrollPane();
			pnlErrores.add(scrollPaneErrores, BorderLayout.CENTER);

			tableErrores = new JTable();
			tableErrores.setDragEnabled(false);
			String[] columnNames = new String[] { "Fila", "Columna", "Lexema",
					"Error" };
			tableErrores.setModel(new DefaultTableModel(columnNames, 0) {
				boolean[] columnEditables = new boolean[] { false, false,
						false, false };

				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			});
			for (int i = 0; i < columnNames.length; i++) {
				tableErrores.getColumnModel().getColumn(i).setResizable(false);
			}
			scrollPaneErrores.setViewportView(tableErrores);

		}

		scrollPane = new JScrollPane();
		this.getContentPane().add(scrollPane);

		String text = "Class classPRUEBA{\r\n/MSumardosnuneros(Int Vara,Int Varb){"
				+ "\r\nReal Varc:\r\nc=Vara/+Varb:\r\nreturn Varc:\r\n}\r\n/"
				+ "MPromedio(Real VarnA,Real VarnB,Real Varn3){\r\nReal VarRes:"
				+ "\r\nVarRes=Varn1/+Varn2/+Varn3:\r\nReturn VarRes_/3:\r\n} }";
		txtPnCodigo = new JTextPane();
		txtPnCodigo.setText(text);
		scrollPane.setViewportView(txtPnCodigo);
		menuBar = new JMenuBar();
		this.setJMenuBar(menuBar);

		mnArchivo = new JMenu("Archivo");
		menuBar.add(mnArchivo);

		mntmNuevo = new JMenuItem("Nuevo");
		mntmNuevo
				.setIcon(new ImageIcon(
						InterfazPrincipal.class
								.getResource("/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/new.png")));
		mntmNuevo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
				InputEvent.CTRL_MASK));
		mnArchivo.add(mntmNuevo);

		mntmAbrir = new JMenuItem("Abrir");
		mntmAbrir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openActionPerformed(e);
			}
		});
		mntmAbrir
				.setIcon(new ImageIcon(
						InterfazPrincipal.class
								.getResource("/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/open.png")));
		mntmAbrir.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
				InputEvent.CTRL_MASK));
		mnArchivo.add(mntmAbrir);

		mntmGuardar = new JMenuItem("Guardar");
		mntmGuardar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveActionPerformed(e);
			}
		});
		mntmGuardar
				.setIcon(new ImageIcon(
						InterfazPrincipal.class
								.getResource("/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/save.png")));
		mntmGuardar.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
				InputEvent.CTRL_MASK));
		mnArchivo.add(mntmGuardar);

		mntmGuardarComo = new JMenuItem("Guardar como...");
		mntmGuardarComo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveAsActionPerformed(e);
			}
		});
		mntmGuardarComo
				.setIcon(new ImageIcon(
						InterfazPrincipal.class
								.getResource("/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/saveAs.png")));
		mntmGuardarComo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
				InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK));
		mnArchivo.add(mntmGuardarComo);

		separator = new JSeparator();
		mnArchivo.add(separator);

		mntmSalir = new JMenuItem("Salir");
		mntmSalir.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,
				InputEvent.ALT_MASK));
		mntmSalir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(JFrame.EXIT_ON_CLOSE);
			}
		});
		mnArchivo.add(mntmSalir);

		mnEjecutar = new JMenu("Ejecutar");
		menuBar.add(mnEjecutar);

		mntmAnalizar = new JMenuItem("Analizar");
		mntmAnalizar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				runActionPerformed(e);
			}
		});
		mntmAnalizar
				.setIcon(new ImageIcon(
						InterfazPrincipal.class
								.getResource("/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/run.png")));
		mnEjecutar.add(mntmAnalizar);
		mntmAnalizar.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
				InputEvent.CTRL_MASK));

		mntmVerAutomatas = new JMenuItem("Ver Automatas");
		mntmVerAutomatas.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				verAutomatas();
			}
		});
		mntmVerAutomatas
				.setIcon(new ImageIcon(
						InterfazPrincipal.class
								.getResource("/co/edu/eam/ingsoft/tlf/analizador/vista/imagenes/search.png")));
		mnEjecutar.add(mntmVerAutomatas);
		mntmVerAutomatas.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
				InputEvent.CTRL_MASK));
	}

}
